/**
 * Collaborative Story Development Web Application (CSDApp) 
 * Copyright Anton Strack 2014
 *
 * This file is part of Collaborative Story Development Application (CSDApp).
 *
 * CSDApp is free software: you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or any later version.
 *
 * CSDApp is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * CSDApp. If not, see <http://www.gnu.org/licenses/>.
 *
 */
package csdwa;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * This class provides database access to the specific resource model. It
 * provides CRUD database functionality and it stores it's results as a list.
 * Additionally, through it's methods, it provides access to determine the table
 * name, and query markers that are set for the particular DAO and thus allows
 * other code a means of interacting with this DAO to execute more advanced
 * queries.
 *
 * @author Anton Strack
 */
public class StateDao extends DaoSupport {

    /**
     * A list of the state beans.
     */
    private List<State> beans;

    /**
     * Construct the RoleDao
     *
     * @param conn the pre-configured connection to the database.
     */
    public StateDao(Connection conn) {
        super(conn);
        this.beans = new ArrayList<State>();
        restoreQueryMarkers();
    }

    /**
     * Select all the beans from the bean table
     *
     * @return the row count indicating if 0 or more beans were retrieved from
     * the database.
     */
    public int selectBeans() {
        int result = 0;
        this.usingQueryMarkers = this.getCoreSelectUsingQueryMarkers();
        this.setMarker(QueryMarker.CORE_CONDITIONS, "1=1");
        try {
            ps = getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, SELECT_QUERY));
            result = executeSelectQuery(ps);
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Select a single bean by it's id.
     *
     * @param id the id number of the bean to select.
     * @return 1 or 0, indicating a bean was retrieved or not.
     */
    public int selectBeanById(int id) {
        int result = 0;
        this.usingQueryMarkers = this.getCoreSelectUsingQueryMarkers();
        this.setMarker(QueryMarker.CORE_CONDITIONS, "state.ID = ?");
        try {
            ps = getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, SELECT_QUERY));
            this.ps.setInt(1, id);
            result = executeSelectQuery(ps);
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Select a single bean by it's id.
     *
     * @param parentId the parent id number of the child beans to select
     * @return the number of returned results or zero if not.
     */
    public int selectStateByResourceTypeId(int parentId) {
        int result = 0;
        this.usingQueryMarkers = this.getCoreSelectUsingQueryMarkers();
        this.setMarker(QueryMarker.CORE_CONDITIONS, "state.ResourceTypeID = ?");
        try {
            ps = getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, SELECT_QUERY));
            this.ps.setInt(1, parentId);
            result = executeSelectQuery(ps);
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Save a bean to the database
     *
     * @param bean the bean to insert. The bean id is not required and won't be
     * used. All other bean values are required.
     * @return the auto-generated id key for the new bean row or 0 on failure.
     */
    public int insertBean(State bean) {
        int result = 0;
        ResultSet rs;
        this.usingQueryMarkers = new ArrayList<QueryMarker>();
        this.usingQueryMarkers.add(QueryMarker.CORE_COLUMNS);
        this.usingQueryMarkers.add(QueryMarker.CORE_TABLE);
        this.usingQueryMarkers.add(QueryMarker.INSERT_VALUES);
        /*
         * HSQLDB cannot properly handle insert statements that have table identifiesr in the form of table.columnName so we need to remove the table name for inserts.
         */
        this.queryMarkers.put(QueryMarker.CORE_COLUMNS, this.prepareInsertColumns(this.getMarker(QueryMarker.CORE_COLUMNS)));
        try {
            this.ps = this.getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, INSERT_QUERY), Statement.RETURN_GENERATED_KEYS);
            this.ps.setNull(1, java.sql.Types.NULL);
            this.ps.setInt(2, bean.getResourceTypeId());
            this.ps.setString(3, bean.getName());
            this.ps.setString(4, bean.getDescription());
            result = this.ps.executeUpdate();
            rs = ps.getGeneratedKeys();
            if (result != 0 && rs.next()) {
                result = rs.getInt(1); // get the auto-generated key from the successful insert operation.
            }
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Update a bean in the database
     *
     * @param bean the bean to update.
     * @return 1 or 0 indicating if the bean was updated or not.
     */
    public int updateBean(State bean) {
        int result = 0;

        this.usingQueryMarkers = new ArrayList<QueryMarker>();
        this.usingQueryMarkers.add(QueryMarker.CORE_CONDITIONS);
        this.usingQueryMarkers.add(QueryMarker.CORE_TABLE);
        this.usingQueryMarkers.add(QueryMarker.UPDATE_COLUMNS_VALUES);
        String[] cols = this.splitStringByCommas(this.COLUMNS_TO_UPDATE);
        this.setMarker(QueryMarker.UPDATE_COLUMNS_VALUES, this.prepareUpdateColumns(cols));
        this.setMarker(QueryMarker.CORE_CONDITIONS, "ID = ?");

        try {
            this.ps = getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, UPDATE_QUERY));
            int index = 1;
            for (String col : cols) {
                if ("name".equalsIgnoreCase(col)) {
                    this.ps.setString(index, bean.getName());
                    index++;
                } else if ("description".equalsIgnoreCase(col)) {
                    this.ps.setString(index, bean.getDescription());
                    index++;
                } else if ("ResourceTypeID".equalsIgnoreCase(col)) {
                    this.ps.setInt(index, bean.getResourceTypeId());
                    index++;
                }
            }
            this.ps.setInt(index, bean.getId()); // where column condition
            result = this.ps.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Deletes the bean from the database
     *
     * @param bean the bean to delete
     * @return 1 or 0 indicating if the bean was deleted or not.
     */
    public int deleteBean(State bean) {
        int result = 0;
        this.usingQueryMarkers = new ArrayList<QueryMarker>();
        this.usingQueryMarkers.add(QueryMarker.CORE_CONDITIONS);
        this.usingQueryMarkers.add(QueryMarker.CORE_TABLE);
        this.setMarker(QueryMarker.CORE_CONDITIONS, "ID = ?");
        try {
            ps = getConn().prepareStatement(this.buildQueryString(usingQueryMarkers, DELETE_QUERY));
            this.ps.setInt(1, bean.getId());
            result = this.ps.executeUpdate();
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }

    /**
     * Get the bean according to the id
     *
     * @param id the id of the table row for the bean
     * @return the bean with the specified id
     */
    public State getById(int id) {
        for (State bean : this.beans) {
            if (bean.getId() == id) {
                return bean;
            }
        }
        return null;
    }

    /**
     * Get the bean according to the name
     *
     * @param name the name of the bean for the table row
     * @return the bean with the specified name
     */
    public State getByName(String name) {
        for (State bean : this.beans) {
            if (bean.getName().equalsIgnoreCase(name)) {
                return bean;
            }
        }
        return null;
    }

    /**
     * Get a list of beans
     *
     * @return a list of action objects
     */
    public List<State> getBeans() {
        return new ArrayList<State>(this.beans);
    }

    /**
     * Add or update a bean in the dao's bean list.
     *
     * @param bean the bean to add
     */
    public void addBeanToDao(State bean) {
        this.beans.add(bean);
    }

    @Override
    public void restoreQueryMarkers() {
        this.setMarker(QueryMarker.CORE_TABLE, "state");
        this.setMarker(QueryMarker.CORE_COLUMNS, "state.ID, state.Name, state.ResourceTypeID, state.Description");
        this.setMarker(QueryMarker.CORE_CONDITIONS, "state.ID = ?");
        this.setMarker(QueryMarker.ORDER_BY_COLUMN, "state.Name");
        this.setMarker(QueryMarker.ORDER_BY_MODE, "ASC");
        this.setMarker(QueryMarker.LIMIT, "");
        this.setMarker(QueryMarker.INSERT_VALUES, "?, ?, ?, ?");
        this.setMarker(QueryMarker.UPDATE_COLUMNS_VALUES, "Name = ?, ResourceTypeID = ?, Description = ?");
        this.COLUMNS_TO_UPDATE = "Name, ResourceTypeID, Description";

    }

    /**
     * Execute the select query and place the results in beans list.
     *
     * @param ps the fully prepared PreparedStatement
     * @return the row count from the select statement
     */
    @Override
    protected int executeSelectQuery(PreparedStatement ps) {
        int result = 0;
        ResultSet rs;
        try {
            rs = this.ps.executeQuery();
            while (rs.next()) {
                State bean = new State();
                bean.setId(rs.getInt("ID"));
                bean.setResourceTypeId(rs.getInt("ResourceTypeID"));
                bean.setName(rs.getString("Name"));
                bean.setDescription(rs.getString("Description"));
                this.beans.add(bean);
                result++;
            }
        } catch (SQLException ex) {
            Logger.getLogger(StateDao.class.getName()).log(Level.SEVERE, null, ex);
        }
        return result;
    }
}
